package com.tensquare.user.service;

import cn.hutool.core.util.StrUtil;
import com.tensquare.user.dao.UserDao;
import com.tensquare.user.pojo.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.IdWorker;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    //1.发送验证码
    public void sendsms(String mobile) {
        //1.生成验证码
        String ran = String.valueOf(Math.random());
        String code=ran.substring(ran.length()-6);
        //2.整合map数据
        Map<String,String> map=new HashMap<>();
        map.put("mobile",mobile);
        map.put("signName","泽易购");
        map.put("templateCode","SMS_195870003");
        map.put("param","{'code':'"+code+"'}");
        //3.通过mq发送消息
        rabbitTemplate.convertAndSend("sms",map);
        //4.存到redis中
        redisTemplate.opsForValue().set(mobile,code);
    }
    //2.判断验证码
    public boolean isCode(String mobile, String code) {
        String code00 = redisTemplate.opsForValue().get(mobile).toString();
        return StrUtil.isNotEmpty(code) && code.equals(code00);
    }
    //3.添加用户
    public void save(User user) {
        user.setId(idWorker.nextId()+"");
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userDao.save(user);
    }
    //4.验证用户名和密码
    public User isTrue(User user) {
        User loginUser = userDao.findByNickname(user.getNickname());
        //第一个为没加密的,第二个为加密的
        if (loginUser!=null && passwordEncoder.matches(user.getPassword(),loginUser.getPassword())){
            return loginUser;
        }
        return null;
    }
    //5.删除用户
    public void delete(String userId) {
        userDao.deleteById(userId);
    }
    //6.修改fans值
    public void updateFans(String id, int count) {
        userDao.updateFans(id,count);
    }
    //7.修改follow值(关注数)
    public void updateFollow(String id, int count) {
        userDao.uodateFollow(id,count);
    }
}
